<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评价时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeEvaluateTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="evaluateList" @selection-change="handleSelectionChange">
      <el-table-column label="订单编号" align="center">
        <template #default="scope">
          <span>{{ displayOrderNo(scope.row.orderId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center">
        <template #default="scope">
          <span>{{ displayShopName(scope.row.shopId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名称" align="center">
        <template #default="scope">
          <span>{{ displayUserName(scope.row.userId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品评分" align="center" prop="evaluateGoodsScore" />
      <el-table-column label="配送评分" align="center" prop="evaluateDeliveryScore" />
      <el-table-column label="评价内容" align="center" prop="evaluateComment" />
      <el-table-column label="评价时间" align="center" prop="evaluateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.evaluateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商家回复内容" align="center" prop="evaluateRelayComment" />
      <el-table-column label="商家回复时间" align="center" prop="evaluateRelayTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.evaluateRelayTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['order:evaluate:remove']">删除</el-button>
          <!-- 商家回复按钮 -->
          <el-button 
            v-if="!scope.row.evaluateRelayComment" 
            link 
            type="success" 
            icon="ChatDotRound" 
            @click="handleReply(scope.row)"
          >
            回复
          </el-button>
          <!-- 修改回复按钮 -->
          <el-button 
            v-else 
            link 
            type="warning" 
            icon="Edit" 
            @click="handleReply(scope.row)"
          >
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 回复对话框 -->
    <el-dialog v-model="replyDialogVisible" title="商家回复" width="500px" append-to-body>
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyRules" label-width="100px">
        <el-form-item label="订单编号">
          <span>{{ replyForm.orderNo }}</span>
        </el-form-item>
        <el-form-item label="评价内容">
          <span>{{ replyForm.evaluateComment }}</span>
        </el-form-item>
        <el-form-item label="回复内容" prop="replyContent">
          <el-input
            v-model="replyForm.replyContent"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmReply" :loading="replyLoading">
            确认回复
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Evaluate">
import { listEvaluate, getEvaluate, delEvaluate, addEvaluate, updateEvaluate } from "@/api/order/evaluate"
import { listShop } from "@/api/order/shop.js";
import { listFrontUser } from "@/api/order/frontUser";
import { listOrders } from "@/api/order/orders.js";
import { listBusiness, getBusiness } from "@/api/order/business.js";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance()
const userStore = useUserStore()

const evaluateList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const daterangeEvaluateTime = ref([])

// 当前用户的shopId
const currentUserShopId = ref(null)
// 是否为管理员用户（userId为1）
const isAdmin = computed(() => userStore.id === 1)

// 回复相关
const replyDialogVisible = ref(false)
const replyLoading = ref(false)
const replyForm = ref({
  evaluateId: null,
  orderId: null,
  orderNo: '',
  evaluateComment: '',
  replyContent: ''
})
const replyRules = {
  replyContent: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
}

// 映射表：ID -> 名称/编号
const orderNoMap = ref({})
const shopNameMap = ref({})
const userNameMap = ref({})

function displayOrderNo(orderId) {
  return orderNoMap.value?.[orderId] ?? orderId
}

function displayShopName(shopId) {
  return shopNameMap.value?.[shopId] ?? shopId
}

function displayUserName(userId) {
  return userNameMap.value?.[userId] ?? userId
}

// 获取当前登录用户的shopId
async function getCurrentUserShopId() {
  try {
    const userId = userStore.id
    console.log('当前用户ID:', userId)
    if (!userId) {
      console.error('未获取到当前用户ID')
      return
    }
    
    // 如果是管理员用户，不需要获取shopId
    if (userId === 1) {
      console.log('当前用户是管理员，可以查看所有店铺评价')
      return
    }
    
    // 根据userId查询business信息
    const businessResponse = await listBusiness({ userId: userId })
    console.log('business查询结果:', businessResponse)
    
    if (businessResponse.rows && businessResponse.rows.length > 0) {
      const business = businessResponse.rows[0]
      currentUserShopId.value = business.shopId
      console.log('当前用户shopId:', currentUserShopId.value)
    } else {
      console.error('未找到当前用户对应的商家信息')
    }
  } catch (error) {
    console.error('获取当前用户商家信息失败:', error)
  }
}

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderId: null,
    shopId: null,
    evaluateComment: null,
    evaluateTime: null,
    evaluateRelayComment: null,
    evaluateRelayTime: null
  },
  rules: {
    orderId: [
      { required: true, message: "订单ID不能为空", trigger: "blur" }
    ],
    shopId: [
      { required: true, message: "店铺ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

// 载入映射数据
async function loadRefMaps() {
  try {
    const [ordersResp, shopsResp, usersResp] = await Promise.all([
      listOrders({ pageNum: 1, pageSize: 9999 }),
      listShop({ pageNum: 1, pageSize: 9999 }),
      listFrontUser({ pageNum: 1, pageSize: 9999 })
    ])

    const orderMap = {}
    ;(ordersResp?.rows || []).forEach(o => {
      if (o && o.orderId != null) orderMap[o.orderId] = o.orderNo || o.orderId
    })
    orderNoMap.value = orderMap

    const sMap = {}
    ;(shopsResp?.rows || []).forEach(s => {
      if (s && s.shopId != null) sMap[s.shopId] = s.shopName || s.shopId
    })
    shopNameMap.value = sMap

    const uMap = {}
    ;(usersResp?.rows || []).forEach(u => {
      if (u && u.userId != null) uMap[u.userId] = u.userName || u.userId
    })
    userNameMap.value = uMap
  } catch (e) {
    // 忽略映射加载错误，表格仍显示原ID
  }
}

/** 查询评价管理列表 */
function getList() {
  loading.value = true
  queryParams.value.params = {}
  if (null != daterangeEvaluateTime && '' != daterangeEvaluateTime) {
    queryParams.value.params["beginEvaluateTime"] = daterangeEvaluateTime.value[0]
    queryParams.value.params["endEvaluateTime"] = daterangeEvaluateTime.value[1]
  }
  
  listEvaluate(queryParams.value).then(response => {
    let filteredList = response.rows
    
    // 如果不是管理员用户，过滤出当前商家的评价
    if (!isAdmin.value && currentUserShopId.value) {
      filteredList = response.rows.filter(evaluate => 
        evaluate.shopId === currentUserShopId.value
      )
      console.log('过滤后的评价数量:', filteredList.length)
    }
    
    evaluateList.value = filteredList
    total.value = filteredList.length
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    evaluateId: null,
    orderId: null,
    shopId: null,
    evaluateGoodsScore: null,
    evaluateDeliveryScore: null,
    evaluateComment: null,
    evaluateTime: null,
    evaluateRelayComment: null,
    evaluateRelayTime: null
  }
  proxy.resetForm("evaluateRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeEvaluateTime.value = []
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.evaluateId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加评价管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _evaluateId = row.evaluateId || ids.value
  getEvaluate(_evaluateId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改评价管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["evaluateRef"].validate(valid => {
    if (valid) {
      if (form.value.evaluateId != null) {
        updateEvaluate(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addEvaluate(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _evaluateIds = row.evaluateId || ids.value
  proxy.$modal.confirm('是否确认删除评价管理编号为"' + _evaluateIds + '"的数据项？').then(function() {
    return delEvaluate(_evaluateIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

// 处理回复
function handleReply(row) {
  replyForm.value = {
    evaluateId: row.evaluateId,
    orderId: row.orderId,
    orderNo: displayOrderNo(row.orderId),
    evaluateComment: row.evaluateComment,
    replyContent: row.evaluateRelayComment || ''
  }
  replyDialogVisible.value = true
}

// 确认回复
async function confirmReply() {
  try {
    // 验证表单
    await proxy.$refs.replyFormRef.validate()
    
    replyLoading.value = true
    
    // 格式化当前时间为后端期望的格式 yyyy-MM-dd HH:mm:ss
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    
    // 更新评价回复
    const updateData = {
      evaluateId: replyForm.value.evaluateId,
      evaluateRelayComment: replyForm.value.replyContent,
      evaluateRelayTime: formattedTime
    }
    
    await updateEvaluate(updateData)
    
    proxy.$modal.msgSuccess('回复成功')
    replyDialogVisible.value = false
    
    // 刷新评价列表
    getList()
    
  } catch (error) {
    console.error('回复失败:', error)
    if (error !== 'cancel') {
      proxy.$modal.msgError('回复失败，请重试')
    }
  } finally {
    replyLoading.value = false
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('order/evaluate/export', {
    ...queryParams.value
  }, `evaluate_${new Date().getTime()}.xlsx`)
}

// 页面初始化
onMounted(async () => {
  console.log('页面开始初始化...')
  console.log('当前用户ID:', userStore.id)
  
  // 获取当前用户信息
  await getCurrentUserShopId()
  
  if (isAdmin.value) {
    console.log('管理员用户，显示所有店铺评价')
  } else if (currentUserShopId.value) {
    console.log('商家用户，只显示当前店铺评价，shopId:', currentUserShopId.value)
  } else {
    console.error('未能获取到用户信息，无法加载数据')
    return
  }
  
  // 加载映射数据
  loadRefMaps()
  // 获取评价列表
  getList()
})
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
